<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item >1170</el-breadcrumb-item>
      <el-breadcrumb-item>设备</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入搜索设备名" v-model="queryInfo.query" clearable @clear="getyyList">
            <el-button slot="append" icon="el-icon-search" @click="queryDevices"></el-button>
          </el-input>
        </el-col>
        <!-- <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加设备</el-button>
        </el-col> -->
      </el-row>
      <el-table :data="pageDevices" border stripe>
        <!-- <el-table-column type="index" label="序号"></el-table-column> -->
        <el-table-column prop="belong" label="所属项目"></el-table-column> 
        <el-table-column prop="county" label="市县" width="60"></el-table-column>
        <el-table-column prop="point" label="监测点"></el-table-column>
        <el-table-column prop="deviceID" label="设备ID"></el-table-column>
        <el-table-column prop="deviceName" label="设备名称"></el-table-column>
        <el-table-column label="问题描述" prop="describle" width="140"></el-table-column>
        <el-table-column prop="pics" label="图片预览" width="80">
          
          <template slot-scope="scope">
            <img src="../../assets/imgs/jp.jpg" slot="reference" v-if="scope.row.pics"  @click="handlePreview(scope.row)" style="width: 50px; height: 50px" />
            <el-dialog title="图片预览" :visible.sync="previewVisible" width="90%" :close-on-click-modal="true">
              <img :src="previewPath" class="preview-img" />
            </el-dialog>
          </template>          
        </el-table-column>        
        <el-table-column label="提出人" prop="proposer" width="60"></el-table-column>
        <el-table-column label="影响" prop="incidence" width="60">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.incidence === '高' || scope.row.incidence === 1" type="warning">高</el-tag>
            <el-tag v-if="scope.row.incidence === '中' || scope.row.incidence === 2" type="primary">中</el-tag>
            <el-tag v-if="scope.row.incidence === '低' || scope.row.incidence === 3" type="info">低</el-tag>  
          </template>          
        </el-table-column>
        <el-table-column label="处理" prop="deal"></el-table-column>
        <el-table-column label="预计解决时间" prop="solve_date" width="100"></el-table-column>
        <el-table-column label="维护日期" prop="maintenance_date" width="100"></el-table-column>
        <el-table-column label="负责人" prop="responsible_person" width="60"></el-table-column>
        <el-table-column label="开放/关闭" width="80">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.question_state" @change="recordStateChange(scope.row)"> </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="设备状态" prop="equipment_status" width="70">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.equipment_status === '在线' || scope.row.equipment_status === 4" type="success">在线</el-tag>
            <el-tag v-if="scope.row.equipment_status === '离线' || scope.row.equipment_status === 5" type="info">离线</el-tag> 
          </template>          
        </el-table-column>    
        <el-table-column label="离线时间" prop="offline_date" width="100"></el-table-column>        
        <el-table-column label="编辑">
          <template slot-scope="scope">
            <!-- <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.index)"></el-button> -->
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="goEditpage(scope.row.index)"></el-button>
            <!-- <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeadById(scope.row.index)"></el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <el-dialog title="添加设备" :visible.sync="addDialogVisible" width="47%" wid :close-on-click-modal="false" @close="addDialogClose">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item label="问题记录" prop="record">
          <el-input v-model="addForm.record"></el-input>
        </el-form-item>
        <el-form-item label="处理" prop="deal">
          <el-input v-model="addForm.record"></el-input>
        </el-form-item>
        <el-form-item label="维护日期" prop="maintenance_date">
          <el-input v-model="addForm.maintenance_date"></el-input>
        </el-form-item>
        <el-form-item label="设备状态" prop="deviceStatus">
          <el-input v-model="addForm.deviceStatus"></el-input>
        </el-form-item>                         
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addyy">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="编辑设备" :visible.sync="editDialogVisible" width="30%" :close-on-click-modal="false" @close="editDialogClose">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px" class="demo-ruleForm">
        <el-form-item label="问题记录" prop="record">
          <el-input v-model="editForm.record"></el-input>
        </el-form-item>
        <el-form-item label="处理" prop="deal">
          <el-input v-model="editForm.deal"></el-input>
        </el-form-item>
        <el-form-item label="维护日期" prop="maintenance_date">
          <el-input v-model="editForm.maintenance_date"></el-input>
        </el-form-item>
        <el-form-item label="设备状态" prop="deviceStatus">
          <el-input v-model="editForm.deviceStatus"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="edityy">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import _ from 'lodash'
import { basePath,uploadPath } from '../../../.env.development'

export default {
  data() {
    return {
      userInfo:null,
      basePath,
      uploadPath,
      previewVisible: false,
      previewPath: '',
      solve_date: '',
      maintenance_date:'',      
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 5,
      },
      yyList: [],
      pageDevices:[],
      total: 0,
      addDialogVisible: false,
      editDialogVisible: false,     
      addForm: {
        county: '',
        point:'',
        deviceID:'',
        deviceName:'',
        record:'',
        deal:'',
        maintenance_date:'',
        deviceStatus:'',
        incidence:'',
        equipment_status: '',
        belong:''
      },
      editForm: {},
      addFormRules: {
        name: [
          { required: true, message: '请输入设备名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur',
          },
        ]
      },
      editFormRules: {
        record: [
          { required: true, message: '请输入设备名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur',
          },
        ]
      },
    }
  },
  created() {
    // this.getDevices(),
    this.userInfo = JSON.parse(sessionStorage.getItem('userInfo'))
    this.getyyList()
  },
  methods: {
    async getDevices() {
      const { data: res } = await this.$http.get('devices/')
      // if (res.meta.status !== 200) {
      //   return this.message.error('获取设备列表失败')
      // }
      this.yyList = res.data.devices
      console.log('设备列表 xx', this.yyList)
      this.total = this.yyList.length
      this.getPageDevices()
    },    
    async getyyList() {
      const { data: res } = await this.$http.get('yy/', {
        params: this.queryInfo,
      })
      // if (res.meta.status !== 200) {
      //   return this.message.error('获取设备列表失败')
      // }
      const xx = JSON.parse(res.data)
      // xx.forEach(item =>{
      //   if(!item.pics){
      //     // this.$set(item,'pics',[])
      //     item.pics = []
      //   }
      //   console.log('设备列表 item pics', item.pics)
      //   if(item.pics.length !== 0){
      //     this.$set(item,'url',basePath + item.pics[0].pic)
      //     console.log('设备列表 pics xx', item)
      //   }
      // })      
      this.yyList = xx
      this.total = res.total,
      this.getPageDevices()
    },
    getPageDevices(){
      this.pageDevices = []
      console.log('getPageDevices total', this.total,this.queryInfo.pagenum)
      // if(this.total<this.queryInfo.pagenum*this.queryInfo.pagesize){
      //   console.log('数据小于pagenum')
      //   this.queryInfo.pagenum = 1
      // }
      for(let i = (this.queryInfo.pagenum - 1)*this.queryInfo.pagesize;i<this.total;i++){
        console.log('pageDevices i', i)
        this.pageDevices.push(this.yyList[i])
        if(this.pageDevices.length === this.queryInfo.pagesize) break;
      }
      console.log('pageDevices', this.pageDevices,this.total)
    },
    async queryDevices() {
      const { data: res } = await this.$http.get('query_devices/', {
        params: this.queryInfo,
      })
      // if (res.meta.status !== 200) {
      //   return this.message.error('获取设备列表失败')
      // }
      this.yyList = res.data.devices
      console.log('查询到的设备列表 xx', this.yyList)
      this.total = res.data.total
      console.log('查询到的设备列表 xx total', this.total)
      this.getPageDevices()
    },
    async recordStateChange(record) {
      console.log('record.question_state', record.question_state)
      const { data: res } = await this.$http.put(`yy/${record.index}/`, record)
      console.log('question_state res', res)
      // if (res.meta.status !== 200) {
      //   userinfo.mg_state = !userinfo.mg_state
      //   return this.$message.error('更新用户状态失败!')
      // }
      if (typeof(res) === 'string') {
        return this.$message.warning(res)
      }
      console.log('record question_state', record.question_state)
      if(record.question_state){
        this.$message.success('问题开放成功')
      }else{
        this.$message.success('问题关闭成功')
      }
      
    },
    handlePreview(file) {
      console.log('eee', file)
      this.previewVisible = true
      this.previewPath = basePath + file.pics[0].pic
    },                  
    handleSizeChange(pagesize) {
      this.queryInfo.pagesize = pagesize
      this.getPageDevices()
    },
    handleCurrentChange(pagenum) {
      this.queryInfo.pagenum = pagenum
      console.log('this.queryInfo.pagenum', this.queryInfo.pagenum)
      this.getPageDevices()
    },
    addDialogClose() {
      this.$refs.addFormRef.resetFields()
    },
    editDialogClose() {
      this.$refs.editFormRef.resetFields()
    },
    addyy() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) {
          return
        }
        const { data: res } = await this.$http.post('yy/', this.addForm)
        if(typeof(res) === 'string'){
            return this.$message.warning(res);
        }
        // if (res.meta.status !== 201) {
        //   return this.$message.error(res.meta.msg)
        // }
        this.addDialogVisible = false
        this.getyyList()
        this.$message.success('添加设备成功')
      })
    },
    edityy() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) {
          return
        }
        const form = _.cloneDeep( this.editForm)
        const { data: res } = await this.$http.put(`/yy/${this.editForm.index}/`, form)
        console.log('edityy1170 res', res)
        // if (res.meta.status !== 200) {
        //   return this.message.error('修改设备失败')
        // }
        if(typeof(res) === 'string'){
          return this.$message.warning(res)
        }           
        this.editDialogVisible = false
        this.getyyList()
        this.$message.success('修改设备成功')
      })
    },
    async showEditDialog(index) {
      console.log('this.editForm.index', index)
      const { data: res } = await this.$http.get(`yy/${index}`)
      // if (res.meta.status !== 200) {
      //   return this.message.error('查询设备失败')
      // }
      console.log('yy edit res', res)
      if(res === '没有权限'){
        return this.$message.warning(res)
      }
      this.editForm = res
      this.editDialogVisible = true
    },
    goEditpage(index){
      this.$router.push('/yy/edit?id='+index)
    },    
    removeadById(index) {
      this.$confirm('确定要删除该设备吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(`yy/${index}`)
          console.log('ad delete res', typeof(res))
          // if (res.meta.status !== 200) {
          //   return this.message.error('删除设备失败')
          // }
          if(res === '没有权限'){
            return this.$message.warning(res)
          }          
          this.getyyList()
          this.$message.success('删除设备成功')
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    }
  },
}
</script>
<style lang="less" scoped>
.preview-img {
  width: 100%
}
.el-select .el-input{
    width: 581px;
  }
</style>
